import axios from "axios";
import router from '../router/index.js'
import store from '../stores/index.js'
import {
	ElMessage
} from 'element-plus';

//没有data属性的请求方式
let httpMethod = [
	'get',
	'delete',
	'head',
	'options'
];


// 创建实例时配置默认值
const http = axios.create({
	baseURL: store.state.url,
	timeout: 1000 * 60 //请求超时时间
});


// 添加请求拦截器
http.interceptors.request.use(function(config) {
	// 添加请求头

	return config;
}, function(error) {
	// 对请求错误做些什么
	return Promise.reject(error);
});


// 添加响应拦截器
http.interceptors.response.use(function(response) {
	// 2xx 范围内的状态码都会触发该函数。
	// 对响应数据做点什么
	if (response.data.code == '401' && response.data.msg.indexOf('机构总数量') == -1) {
		// localStorage.setItem("token", '');

		router.replace('/login');
		return Promise.reject(response.data.msg);
	}

	return response;
}, function(error) {
	// 超出 2xx 范围的状态码都会触发该函数。
	// 对响应错误做点什么
	return Promise.reject(error);
});

/**
 * url:请求地址
 * method：请求方式（默认get）
 * params：请求数据（默认空）
 * config：请求配置（默认空）
 */
const httpRequest = (url, method = "get", params = {}, config = {}) => {
	//字符串转小写
	method = method.toLowerCase();

	//如果未开启配置，直接传递配置js对象。
	if (JSON.stringify(config) == "{}") {
		return http[method](url, httpMethod.indexOf(method) != -1 ? {
			params: params
		} : params);
	}

	/**
	 * 如果开启配置，区分get、post请求传递值
	 * get: 合并参数
	 * post：正常传递值
	 */
	return httpMethod.indexOf(method) != -1 ? http[method](url, {
		...config,
		params: params
	}) : http[method](url, params, config);

}

//异步Http请求
const asyncHttp = (url, params = {}, config = {}, method = "get") => {
	config = {
		...config,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	}

	return send(url, method, params, config);
}

//异步Http请求
const asyncHttpConfig = (config = {}, method = "post") => {
	config = {
		...config,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	}
	return send(config.url, method, config.data, config);
}

//异步Http请求
const asyncHttpJson = (url, params = {}, config = {}, method = "post") => {
	config = {
		...config,
		headers: {
			'Content-Type': 'application/json',
		},
	}

	return send(url, method, params, config);

}

function send(url, method = "get", params = {}, config = {}) {
	//字符串转小写
	method = method.toLowerCase();

	return new Promise((resolve, reject) => {

		let promise = httpRequest(url, method, params, config);

		//返回结果处理
		promise.then(({
			data: res
		}) => {
			if (res.code == 500 || res.code == 'error' || res.code == 'err') {
				return ElMessage.error({
					message: res.msg
				});
			}
			//请求处理成功获取结果
			resolve(res);



		}).catch((error) => {
			//自定义异常处理
			console.log("error", error);
			ElMessage.warning({
				message: "操作未成功,请重试"
			});
		})

	}).then((value) => {
		//返回成功结果
		return value;
	})
}

export {
	http,
	httpRequest,
	asyncHttp,
	asyncHttpJson,
	asyncHttpConfig
}